package dq.study.designmodel.iteator;

/**
 * @author dongqun
 * @Description:
 * @date 2019/3/13 22:25
 */
public class LinkedList<E> implements Collection<E> {
    Node<E> first;
    Node<E> last;
    int index;
    @Override
    public void add(E e) {
        Node<E> node = new Node<E>();
        node.setData(e);
        if (first==null){
            first = node;
            last = node;
        }else {
            last.setNext(node);
            last = node;
        }
        index++;
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public Iterator<E> iterator() {
        return new LinkedListIterator<E>();
    }

    private class LinkedListIterator<E> implements Iterator<E>{

        private Node currentNode = first;
        private boolean isFirst = true;
        @Override
        public boolean hasNext() {
            if (currentNode.getNext()==null) return false;
            return true;
        }

        @Override
        public E next() {
           if (isFirst){
               currentNode = first;
               isFirst = false;
               return (E)currentNode.getData();
           }
           currentNode = currentNode.next;
           return (E) currentNode.getData();
        }
    }
}
